// connect 是一个装饰器，需要返回一个hoc
// hoc 的使用：const EnhanceCmp = Hoc(Cmp);  hoc 返回的又是一个组件

// export default function connect(mapStateToProps, mapDispatchToProps) {
//   return (WrapperComponent) => {
//     return function EnhanceComponent(props) {};
//   };
// }

import { useContext, useLayoutEffect } from 'react';
import useDispatch from '../hooks/useDispatch';
import ReactReduxContext from './Context';
import useForceUpdate from '../hooks/useForceUpdate';
import bindActionCreators from '../bindActionCreators';

// 上面的简写
const connect = (mapStateToProps, mapDispatchToProps) => (WrapperComponent) => (props) => {
  const forceUpdate = useForceUpdate();

  const store = useContext(ReactReduxContext);
  const dispatch = useDispatch();

  const stateProps = mapStateToProps(store.getState());
  let dispatchProps = { dispatch };
  if (typeof mapDispatchToProps === 'function') {
    dispatchProps = mapDispatchToProps(dispatch);
  } else if (typeof mapDispatchToProps === 'object') {
    dispatchProps = bindActionCreators(mapDispatchToProps, dispatch);
  }

  // 扣点细节，在dom变更之前就订阅
  useLayoutEffect(() => {
    const unsubscribe = store.subscribe(() => {
      forceUpdate();
    });
    return () => {
      unsubscribe && unsubscribe();
    };
  }, [store]);

  return <WrapperComponent {...props} {...stateProps} {...dispatchProps} />;
};
export default connect;
